package cn.regexp.canal.handler;

import cn.regexp.canal.domain.OrderInfo;
import cn.regexp.canal.enums.SeckillRedisKeyEnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * @author Regexpei
 * @date 2024/7/6 16:35
 * @description 订单信息处理器
 */
@Slf4j
@Component
@CanalTable(value = "t_order_info")
public class OrderInfoHandler implements EntryHandler<OrderInfo> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void insert(OrderInfo orderInfo) {
        log.info("Insert order message, orderInfo: {}", JSON.toJSONString(orderInfo));
        // 往 redis 中存储订单信息
        redisTemplate.opsForHash().put(SeckillRedisKeyEnum.SECKILL_ORDER_HASH.getRealKey(""), orderInfo.getOrderNo(),
                JSON.toJSONString(orderInfo));
    }

    @Override
    public void update(OrderInfo before, OrderInfo after) {
        log.info("Update order message, before: {}, after{}", JSON.toJSONString(before), JSON.toJSONString(after));
        // 更新 redis 中订单信息
        redisTemplate.opsForHash()
                .put(SeckillRedisKeyEnum.SECKILL_ORDER_HASH.getRealKey(""), after.getOrderNo(), after);
    }

    @Override
    public void delete(OrderInfo orderInfo) {
        log.info("Delete order message, orderInfo: {}", JSON.toJSONString(orderInfo));
        // 删除 redis 中订单信息
        redisTemplate.opsForHash()
                .delete(SeckillRedisKeyEnum.SECKILL_ORDER_HASH.getRealKey(""), orderInfo.getOrderNo());
    }

}
